<?php
/**
 * Created by PhpStorm.
 * User: zhaoyi
 * Date: 2022/1/26
 * Time: 11:46.
 */

declare(strict_types=1);

namespace App\Application\Api\Controller;

use App\Annotation\Api;
use App\Application\Admin\Model\Member;
use App\Application\Admin\Model\Store;
use App\Application\Admin\Service\AdminSettingService;
use App\Application\Admin\Service\CityService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Controller;

#[Controller("/api/Sign")]
class SignController extends AbstractController
{
    #[Inject]
    protected AdminSettingService $setting;


    #[Api]
    #[PostMapping("getopenid")]
    function getopenid()
    {
        $code = $this->request->input('code', '');
        if ($code) {
            $params = array();
            $params['appid'] = $this->setting->getSiteSetting('app_id');
            $params['secret'] = $this->setting->getSiteSetting('app_secret');
            $params['code'] = $code;
            $params['grant_type'] = 'authorization_code';
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $params['appid'] . '&secret=' . $params['secret'] . '&js_code=' . $code . '&grant_type=authorization_code';
            $info = $this->postApiJson($url, $params);
            return $info ? $this->returnSuccessJson(compact('info')) : $this->returnErrorJson();
        } else {
            return $this->returnErrorJson();
        }
    }

    #[Api]
    #[PostMapping("threelogin")]
    public function threelogin()
    {

        $appid = $this->request->header('appid', '');
        $token = self::getRandChar(32);
        $data = array(
            'nickname' => $this->request->input('nickName', ''),
            'gender' => $this->request->input('gender', ''),
            'avatar' => $this->request->input('avatarUrl', ''),
            'create_time' => time(),
            'openid' => $this->request->input('openid', ''),
            'appid' => $appid,
            'token' => $token,
        );
        $member = Member::where('openid', $this->request->input('openid', ''))->where('appid', $appid)->select('*')
            ->first() ?: [];
        $res = Member::updateOrCreate(['member_id' => $member['member_id']], $data);

        // 查询是否存
        return $res ? $this->returnSuccessJson(compact('res')) : $this->returnErrorJson();
    }


}